<?php

/**
 * 普通用户个人中心
 */
class CustomerCenterController extends CenterController {
	
    /**
     * GET: 显示当前登录用户信息
     * POST: 更新当前登录用户信息
     * 
     * 用户信息
     */
    public function info()
    {
        $this->user->load('lawyer');
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $posts = Input::all();

            $rules = array (
                'sex' => array('regex:/^(male|female)$/i')
            );
            $messages = array(
                'sex.regex' => '性别选项错误'
            );

            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }
            
            // save
            try {
                $user = User::updateUser($this->user->id, $posts);
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '咨询律师失败，请稍后再试。',
                    503
                );
            }
        } else {
            $user = $this->user->toArray();
        }
        
        $userArr = [];
        $userArr['id'] = $user['id'];
        $userArr['nikname'] = $user['nikname'];
        $userArr['realname'] = $user['realname'];
        $userArr['phone'] = $user['phone'];
        $userArr['email'] = $user['email'];
        $userArr['score'] = $user['score'];
        $userArr['status'] = $user['status'];
        $userArr['province'] = $user['province'];
        $userArr['city'] = $user['city'];
        $userArr['district'] = $user['district'];
        $userArr['money'] = round(Wallet::getMoney($this->user->id));
        $userArr['avatar'] = UtilsHelper::getImage($user['avatar'], "img/dfimg.png");
        $userArr['unread_counts'] = $this->getUnreadCounts($this->user);
        return $this->makeView('center.customer.info', $userArr);
    }
    
    protected function getUnreadCounts($user) {
        $unreadCounts = [];
        $status = [
            Post::STATUS_NEW, 
            Post::STATUS_REPLIED, 
            Post::STATUS_WAIT_FOR_EVALUATION, 
            Post::STATUS_COMPLETE, 
            Post::STATUS_CANCELLED];
        $unreadCounts['question'] = Post::getUnreadCountForCreator($user->id, [Post::TYPE_QUESTION], $status);
        $unreadCounts['pay_text'] = Post::getUnreadCountForCreator($user->id, [Post::TYPE_PAY_TEXT], $status);
        $unreadCounts['pay_phone'] = Post::getUnreadCountForCreator($user->id, [Post::TYPE_PAY_PHONE], $status);
        $unreadCounts['pay_company'] = Post::getUnreadCountForCreator($user->id, [Post::TYPE_PAY_COMPANY], $status);
        $types = [Post::TYPE_PAY_TEXT, Post::TYPE_PAY_PHONE, Post::TYPE_PAY_COMPANY];
        $unreadCounts['shopping'] = Post::getUnreadCountForCreator($user->id, $types, [Post::STATUS_WAIT_PAY]);
        $unreadCounts['letter'] = StationLetterUser::getUnreadCount();
        return $unreadCounts;
    }
    
    /**
     * 上传头像
     */
    public function updateUserImage() {
       $rules = array(
            'user_id' => 'required|exists:user,id',
            'upload_file' => 'required',
        );
        $messages = array(
            'user_id.exists' => '这个用户不存在',
            'upload_file.required' => '请上传图片',
        );

        $posts = Input::all();
        $validator = Validator::make ( $posts, $rules, $messages );
        if ($validator->fails()) {
            return $this->makeView(
                'errors.400', 
                $validator->errors(),
                400
            );
        }

        $avatar_folder = Config::get('app.upload_dir') . '/user_img/' . $posts['user_id'];
        $upload_folder = UploadHelper::getFileFolder($avatar_folder);
        try {
            $upload_result  = UploadHelper::uploadImage('upload_file', $upload_folder);
            if ($upload_result['error'] == 0) {
            } else {
                throw new Exception('上传图片失败。');
            }
        } catch(Exception $ex) {
            Log::error($ex);
            return $this->makeView(
                'errors.503', 
                '上传图片失败，请稍后再试。',
                503
            );
        }

        $user = User::find($posts['user_id']);
        $user->avatar = $avatar_folder . "/" . $upload_result['files'][0]['basename'] . "." . $upload_result['files'][0]['ext'];
        $user->save();

        return $this->makeView ( 'general.200', array('file_path' => $user->avatar), 200 );
    }
    /**
     * 上传律师背景图片
     */
    public function updateLawyerBgImage() {
            $rules = array(
                'user_id' => 'required|exists:lawyer,user_id',
                'upload_file' => 'required',
            );
            $messages = array(
                'user_id.exists' => '这个律师不存在',
                'upload_file.required' => '请上传图片',
            );

            $posts = Input::all();
            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }

            $upload_folder = Config::get('app.upload_dir').'/user_img/'.$posts['user_id'];
            try {
                $upload_result  = UploadHelper::uploadImage('upload_file', $upload_folder);
                if ($upload_result['error'] == 0) {
                } else {
                    throw new Exception('上传图片失败。');
                }
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '上传图片失败，请稍后再试。',
                    503
                );
            }
            $lawyer = Lawyer::find($posts['user_id']);
            $lawyer->bg_image = $upload_result['files'][0]['path'];
            $lawyer->save();
            return $this->makeView ( 'general.200', '成功上传用户图片', 200 );
     }

    /**
     * 我的跟贴
     */
    public function articles() {
        $articles = Article::leftJoin('evaluate', 'evaluate.item_id', '=', 'articles.id')
            ->leftJoin('user', 'user.id', '=', 'articles.creator_id')
            ->where('evaluate.creator_id', $this->user->id)
            ->select(
                'articles.title', 
                'evaluate.comment', 
                'evaluate.created_at',
                'user.avatar as creator_avatar',
                'user.id as creator_id',
                'user.realname as creator_realname'
                )
            ->get();
        $articleArr = $articles->toArray();
        foreach($articleArr as &$article) {
            $article['creator_avatar'] = UtilsHelper::getImage($article['creator_avatar'], "img/dfimg.png");
        }
        return $this->makeView('center.customer.articles', $articleArr);
    }

    /**
     * 普通用户称为成为律师
     */
    public function becomeLawyer() {
        $this->user->load('lawyer');
        $user = $this->user;
        if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
            $rules = array (
                'realname' => 'required',
                'province' => 'required',
                'city' => 'required',
                'district' => 'required',
                'address' => 'required',
                // 'avatar' => 'required',
                'license' => 'required',
                'license_file' => 'required',
                'ID_img' => 'required',
                'work_scope' => 'required|array',
                'company_name' => 'required',
                'practice_period' => array('required', 'regex:/^(1to3|3to5|5to10|10)$/i'),
                'text_reply_fee' => 'required|integer',
                'phone_reply_fee' => 'required|integer'
            );
            $messages = array(
                'realname.required' => '请填写姓名',
                'province.required' => '请选择所在地省份',
                'city.required' => '请选择所在地城市',
                'district.required' => '请选择所在地地区',
                'address.required' => '请填写所在地详细地址',
                // 'avatar.required' => '请上传个人图片',
                'license.required' => '请填写律师证号',
                'license_file.required' => '请上传律师证',
                'ID_img.required' => '请上传身份证',
                'work_scope.required' => '请选择擅长的领域',
                'work_scope.array' => '擅长的领域要是数组',
                'company_name.required' => '请填写律师事务所得名字',
                'practice_period.required' => '请选择律师的执业年限',
                'practice_period.regex' => '律师的执业年限值不正确',
                'text_reply_fee.required' => '请填写图文咨询的价格',
                'text_reply_fee.integer' => '图文咨询的格式要是数字',
                'phone_reply_fee.required' => '请填写语音咨询的价格',
                'phone_reply_fee.integer' => '语音咨询的格式要是数字',
            );
            $posts = Input::all();
            $validator = Validator::make ( $posts, $rules, $messages );
            if ($validator->fails()) {
                // the given data did not pass validation
                return $this->makeView(
                    'errors.400', 
                    $validator->errors(),
                    400
                );
            }
            
            // save
            try {
                $user = User::addLawyer($this->user->id, $posts);
                $user->load('lawyer');
            } catch(Exception $ex) {
                Log::error($ex);
                return $this->makeView(
                    'errors.503', 
                    '成为律师失败，请稍后再试。',
                    503
                );
            }

            // 成功以后提示需要等待验证
        }
        \Illuminate\Support\Facades\Event::fire('become_lawyer', $user);
        $workScopeList = UtilsHelper::workScope();
        return $this->makeView('center.customer.become_lawyer', 
            array(
                'user' => $user->toArray(),
                'work_scope' => $workScopeList
            )
        );
    }
    
    /**
     * 我关注的律师
     */
    public function lawyerFollowed() {
		$follows = Lawyer::leftJoin('follows', 'lawyer.user_id', '=', 'follows.follow_id')
            ->leftJoin('user', 'user.id', '=', 'lawyer.user_id')
            ->select(
                'user.id', 
                'user.avatar', 
                'user.score',
                'user.likes_count',
                'user.collects_count',
                'user.status',
                'user.realname', 
                'user.nikname', 
                'user.province', 
                'user.city', 
                'user.district', 
                'user.address', 
                'user.signature', 
                'user.follows_count',
                'lawyer.introduce',
                'lawyer.experience',
                'lawyer.practice_period', 
                'lawyer.work_scope',
                'lawyer.case_count',
                'lawyer.service_time',
                'lawyer.bg_image',
                'lawyer.is_recommended',
                'lawyer.average_evaluate_score',
                'lawyer.position',
                'lawyer.free_reply_count',
                'lawyer.pay_reply_count',
                'text_reply_fee',
                'phone_reply_fee',
                'follows.created_at'
            )
            ->where('follows.user_id', Auth::user()->id)
            ->where('follows.follow_stat', Follow::FOLLOWED)
            // ->take($limit)
            // ->skip($offset)
            ->orderBy('follows.updated_at', 'DESC')
			->get();
        $followsArr = $follows->toArray();
        foreach($followsArr as &$follow) {
            $follow['city'] = AreaHelper::areaCodeToName($follow['city']);
            $follow['district'] = AreaHelper::areaCodeToName($follow['district']);
            $follow['province'] = AreaHelper::areaCodeToName($follow['province']);
            $follow['avatar'] = UtilsHelper::getImage($follow['avatar'], "img/dfimg.png");
            $follow['work_scope'] = UtilsHelper::getActualWorkScopes($follow['work_scope']);
            $follow['practice_period'] = UtilsHelper::getPracticePeriodStr($follow['practice_period']);
            $follow['text_reply_fee'] = $follow['text_reply_fee'];
            $follow['phone_reply_fee'] = $follow['phone_reply_fee'];
			Log::info("################### avatar=".$follow['avatar']);
        }
        return $this->makeView('center.customer.mylawyer.followed', $followsArr);
    }

    /**
     * 罗列“全部”了的咨询
     */
    public function questionAll()
    {
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('evaluate', 'evaluate.item_id', '=', 'posts.id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.created_at',
                'posts.updated_at',
                'evaluate.score as evaluate_score',
                'evaluate.comment as evaluate_comment')
            ->where('posts.type',Post::TYPE_QUESTION)
            ->where('posts.creator_id', Auth::user()->id)
            ->where('posts.customer_visible', Post::CUSTOMER_VISIBLE)
            ->orderBy('posts.updated_at', 'DESC')
            ->groupBy('posts.id')
            // ->take($limit)
            // ->skip($offset)
            ->get();
        $questionArr = $questions->toArray();
        foreach($questionArr as &$question){
	$question['status_code'] = $question['status'];
            $question['status'] = UtilsHelper::getPostStatusStr($question['status']);
            $question['post_category'] = UtilsHelper::getWorkScopeName($question['post_category']);
            $question['transitions'] = $this->getAvailableTransitions($question['status']);
        }
        $questionArr = $this->addComments($questionArr);
        return $this->makeView('center.customer.question.complete', $questionArr);
    }

    protected function getAvailableTransitions($status)
    {
        $transitions = [];
        switch($status) {
            case 'new':
                $transitions[] = 'cancel';
            break;
            case 'replied':
                $transitions[] = 'contact';
                $transitions[] = 'confirm';
            break;
            case 'wait_for_evaluation':
                $transitions[] = 'evaluate';
            break;
            case 'complete':
                $transitions[] = 'delete';
                $transitions[] = 'tip';
            break;
            case 'cancelled':
            break;
            case 'refused':
            break;
        }
        return $transitions;
    }
    
    /**
     * 罗列“已经完成”了的咨询
     */
    public function questionComplete()
    {
        $questionArr = $this->getQuestionListByStatus(Post::STATUS_COMPLETE);
        return $this->makeView('center.customer.question.complete', $questionArr);
    }

    /**
     * 罗列“待评价”的咨询
     */
    public function questionWaitForEvaluation()
    {
        $questionArr = $this->getQuestionListByStatus(Post::STATUS_WAIT_FOR_EVALUATION);
        return $this->makeView('center.customer.question.waitforevaluation', $questionArr);
    }

    /**
     * 罗列“已被受理（抢单）“的问题
     */
    public function questionReplied() {
        $questionArr = $this->getQuestionListByStatus(Post::STATUS_REPLIED);
        return $this->makeView('center.customer.question.replied', $questionArr);
    }

    /**
     * 罗列“待抢单”的问题
     */
    public function questionNew() {
        $questionArr = $this->getQuestionListByStatus(Post::STATUS_NEW);
        return $this->makeView('center.customer.question.new', $questionArr);
    }
    
    /**
     * 罗列“已取消”的问题
     */
    public function questionCancelled() {
        $questionArr = $this->getQuestionListByStatus(Post::STATUS_CANCELLED);
    	return $this->makeView('center.customer.question.new', $questionArr);
    }

    protected function getQuestionListByStatus($status) {
        $questions = Post::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
            'posts.id',
            'posts.title',
            'posts.content',
            'posts.status',
            'posts.post_category',
            'posts.created_at',
            'posts.updated_at',
            'post_thread.user_id as lawyer_id')
            ->where('posts.status', $status)
            ->where('posts.type',Post::TYPE_QUESTION)
            ->where('posts.creator_id', Auth::user()->id)
            ->where('posts.customer_visible', Post::CUSTOMER_VISIBLE)
            ->orderBy('posts.updated_at', 'DESC')
            ->groupBy('posts.id')
            // ->take($limit)
            // ->skip($offset)
            ->get();
        $questionArr = $questions->toArray();
        foreach($questionArr as &$question){
			$question['status_code'] = $question['status'];
            $question['transitions'] = $this->getAvailableTransitions($question['status']);
            $question['status'] = UtilsHelper::getPostStatusStr($question['status']);
            $question['post_category'] = UtilsHelper::getWorkScopeName($question['post_category']);
        }
        $questionArr = $this->addComments($questionArr);
        return $questionArr;
    }
    
    public function getQuestion($id){
    	$post = Post::find($id);
    	if(!$post){
			return;
    	}
    	if($post->creator_id == Auth::user()->id){
    		return $post;
    	}
    	return;
    }
    
    public function toEvaluate($id){
    	$question = $this->getQuestion($id);
    	if(!$question){
            return $this->makeView('errors.400', '请求错误', 400);
    	}
    	if($question->status != Post::STATUS_WAIT_FOR_EVALUATION){
    		if($question->type == Post::TYPE_QUESTION){
    			return Redirect::Route('center.customer.question.view',$id);
    		}else{
    			return Redirect::Route('pay.center.customer.question.view',$id);
    		}
    	}
    	if($question->type == Post::TYPE_QUESTION){
    		return $this->makeView('center.customer.question.waitforcomment_xq',['id' => $id]);
    	}else{
    		return $this->makeView('center.customer.order.waitforcomment_xq',['id' =>$id]);
    	}
    }
    
    /**
     * 咨询详细
     */
    public function questionView($id){
        $post = $this->getQuestion($id);
        if(!$post){
        	return $this->makeView('errors.400', '请求错误', 400);
        }
        $post->load('postAttach');
        $data=array();
        $data['post_id'] = $id;
        $data['type'] = $post->getType();
		$data ['post_category'] = $post->getPostCatKey();
        $data['title'] = $post->title;
        $data['content'] = $post->content;
		$data['status_code'] = $post->status;
        $data['status'] = $post->getStatus();
        $data['created_at'] = $post->created_at;
        $data['updated_at'] = $post->updated_at;
        $data['lawyer'] = $post->getLawyerName();
        $data['comments'] = $post->getComments();
        $data['postAttachs'] = $post->postAttach->toArray();
        return $this->makeView('center.customer.question.view', $data);
    }
    
    /**
     * 我咨询过的律师
     */
    public function lawyerConsulted() {
        $questions = Post
            ::leftJoin('post_thread', 'posts.id', '=', 'post_thread.post_id') 
            ->leftJoin('user', 'user.id', '=', 'posts.creator_id')
            ->select(
                'posts.id',
                'posts.title',
                'posts.content',
                'posts.status',
                'posts.post_category',
                'posts.created_at',
                'user.id as creator_id', 
                'user.avatar as creator_avatar', 
                'user.realname as creator_realname'
            )
            ->where('type', Post::TYPE_QUESTION)
            ->where('posts.status', Post::STATUS_REPLIED)
            ->where('posts.creator_id', Auth::user()->id)
            ->orderBy('posts.updated_at', 'DESC')
            // ->take($limit)
            // ->skip($offset)
            ->get();
        $questionArr = $questions->toArray();
        $questionArr = $this->addComments($questionArr);
        return $this->makeView('center.customer.mylawyer.consulted', $questionArr);
    }

    /**
     * 已和我有成交的律师
     * - 通过有向律师的订单
     */
    public function lawyerOrdered() {
        $this->layout->content = View::make('center.customer.mylawyer.ordered');
    }

    /**
     * 钱包提现
     */
    public function walletMoneyOut() {
        $this->layout->content = View::make('center.wallet.moneyout');
    }

    /**
     * 我的商品
     */
    public function customerCommodity() {
        $this->layout->content = View::make('center.customer.commodity');
    }

    /**
     * 我的订单
     */
    public function myOrder() {
        $this->layout->content = View::make('center.customer.my_order');
    }


    /**
     * 我的咨询
     */
    public function myQuestion() {
        $this->layout->content = View::make('center.customer.my_question');
    }


    /**
     * 免费咨询
     */

    public function freeQuestion($status) {
        // $data=array();
        // $data['status'] = $status;
        // return $this->makeView('center.customer.question_order.free_question', $data);
        $this->layout->content = View::make('center.customer.question_order.free_question', ['status' => $status]);
    }


    /**
     * 图文咨询
     */
    public function payText($status) {
        $this->layout->content = View::make('center.customer.question_order.pay_text', ['status' => $status]);
    }

    /**
     * 电话咨询
     */
    public function payPhone($status) {
        $this->layout->content = View::make('center.customer.question_order.pay_phone', ['status' => $status]);
    }


    /**
     * 小薇企服
     */
    public function payCompany($status) {
        $this->layout->content = View::make('center.customer.question_order.pay_company', ['status' => $status]);
    }

    /**
     * 订单详情
     */
    public function orderView($id) {
        $post = $this->getQuestion($id);
        if(!$post){
            return $this->makeView('errors.400', '请求错误', 400);
        }
        $post->load('postAttach');
        $data=array();
        $data['post_id'] = $id;
        $data['type'] = $post->getType();
        $data ['post_category'] = $post->getPostCatKey();
        $data['title'] = $post->title;
        $data['content'] = $post->content;
        $data['status_code'] = $post->status;
        $data['status'] = $post->getStatus();
        $data['created_at'] = $post->created_at;
        $data['updated_at'] = $post->updated_at;
        $data['lawyer'] = $post->getLawyerName();
        $data['comments'] = $post->getComments();
        $data['postAttachs'] = $post->postAttach->toArray();
        return $this->makeView('center.customer.question_order.view', $data);
        // $this->layout->content = View::make('center.customer.question_order.view', ['id' => $id]);
    }
}